﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
using System.IO;
using KeanuMvc.Reference;
using HIS.Utils.Securities;
using HIS.Utils;
using HISModels.Entities;
using System.Configuration;
using Newtonsoft.Json.Linq;
using HISModels.ViewModel;
namespace HIS.Controllers.Master
{
    public class Employees : HIS.Controllers.AppBaseController
    {
        #region Fields

        private string strAction = string.Empty;
        private string strNotification = string.Empty;
        private Employee employee = null;

        #endregion

        #region Employeer
        public Employees()
        {
            Data.Add("Pagetitle", "Employee");
            Data.Add("Notification", strNotification);
        }

        [Authorization(RoleAction = "master-items")]
        public override void Index()
        {
            try
            {

                Data["Pagetitle"] += " :: Employee List";
                Data.Add("ddlLocation2", DropDownLocation2(""));
                RenderFile("master\\employee\\employee.html");
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write(ex.Message);
            }
        }


        [Authorization(RoleAction = "master-items")]

        public void TableList()
        {
            try
            {

                string strJson = string.Empty;
                string sEcho = HttpContext.Current.Request["sEcho"];
                string EmployeeNumber = HttpContext.Current.Request["employeenumber"].NullSafeToString();
                string Fullname = HttpContext.Current.Request["Fullname"].NullSafeToString();
                string HospitalUnitId = HttpContext.Current.Request["HospitalUnitId"].NullSafeToString();
                //int location = Convert.ToInt32(HttpContext.Current.Request["location"].NullSafeToString());

                //string ssearch = "nama=" + namevalue;
                string ssearch = "employeenumber=" + EmployeeNumber + ";nama=" + Fullname + ";HospitalUnitId=" + HospitalUnitId; ;

                PostDataTablesNet pagingSearch = new PostDataTablesNet();
                pagingSearch.iDisplayLength = Convert.ToInt32(HttpContext.Current.Request["iDisplayLength"]);
                pagingSearch.iDisplayStart = Convert.ToInt32(HttpContext.Current.Request["iDisplayStart"]);
                pagingSearch.sEcho = Convert.ToInt32(HttpContext.Current.Request["sEcho"]);
                //pagingSearch.sSearch = HttpContext.Current.Request["sSearch"];
                if (!string.IsNullOrEmpty(ssearch))
                {
                    pagingSearch.sSearch = ssearch;
                }
                else { pagingSearch.sSearch = Convert.ToString(HttpContext.Current.Request["sSearch"]); }
                pagingSearch.sSearch = ssearch;

                string strUri = string.Empty;
                strUri = Global.ServiceUriDictionary["employeepaging"] + Global.ServiceUriDictionary["requestformat"];
                StringReader stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(pagingSearch));


                strJson = stringReader.ReadToEnd();
                stringReader.Dispose();
                base.RestService.Dispose();


                HttpContext.Current.Response.Write(strJson);

            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write(ex.Message);
            }
        }


        [Authorization(RoleAction = "master-items")]
        //edit oke
        public void EditEmployee()
        {
            StringReader stringReader = null;
            /// Get id record from querystring
            employee = new Employee();
            Utils.Helper.SetNullToEmptyString(employee);
            int id = 0;
            try
            {
                id = Convert.ToInt32(HttpContext.Current.Request["id"]);
            }
            catch
            {
                /// Throw to list if something goes wrong
                GoToUrl("employees/"); return;
            }

            try
            {
                ///Set Rest Url///
                string strUri = Global.ServiceUriDictionary["employeedetail"] + id + Global.ServiceUriDictionary["requestformat"];
                ///Get Rest///
                stringReader = base.RestService.GetJson(strUri);
                ///Deserialize json response to object///
                employee = JsonConvert.DeserializeObject<Employee>(stringReader.ReadToEnd());
                Data.Add("ddlLocation", DropDownLocation(employee.HospitalUnitId.NullSafeToString()));
                Data.Add("ddlDepartment", DropDownDepartment(employee.DepartementId.NullSafeToString()));
                Data.Add("ddlGender", Utils.Helper.GetGender("GenderId", "class=required", employee.GenderId.ToString()));
                ///Set variable for rendering on view HTML///
                Data["Pagetitle"] += " :: Edit Employee";
                Data.Add("employee", employee);
                Data.Add("IsCreate", "false");
                Data["Notification"] = strNotification;

            }
            catch (Exception ex)
            {
                Data["Notification"] = Helper.ErrorMessage(ex.Message);
            }
            finally
            {
                RenderFile("Master\\employee\\editemployee.html");
                if (stringReader != null) stringReader.Dispose();
                base.RestService.Dispose();
            }
        }


        [Authorization(RoleAction = "master-items")]

        //Delete belum
        public void DeleteEmployee()
        {
            StringReader stringReader = null;
            int id = 0;
            try
            {
                id = Convert.ToInt32(HttpContext.Current.Request["id"]);
            }
            catch
            {
                GoToUrl("employees/");
                return;
            }

            try
            {
                employee = new HISModels.Entities.Employee();
                string strUri = Global.ServiceUriDictionary["employee"] + Global.ServiceUriDictionary["requestformat"];

                stringReader = base.RestService.DeleteJson(strUri, JsonConvert.SerializeObject(id));
                employee = JsonConvert.DeserializeObject<Employee>(stringReader.ReadToEnd());
                if (strNotification == string.Empty) strNotification = Helper.SuccessMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                Data["Notification"] = strNotification;

            }
            catch (Exception ex)
            {
                Data["Notification"] = Helper.ErrorMessage(ex.Message);
            }
            finally
            {
                //RenderFile("Admins\\Actions\\editgroupspecialist.html");
                //stringReader.Dispose();
                //base.RestService.Dispose();

                HttpContext.Current.Response.Write(strNotification);
                //HttpContext.Current.Response.Redirect(Data["rooturl"] + "master/employees/");

                //GoToUrl("groupspecialist/");

                base.RestService.Dispose();
            }
        }




        [Authorization(RoleAction = "master-items")]
        //save oke
        public void SaveEmployee()
        {
            StringReader stringReader = null;
            string strUri = string.Empty;
            try
            {
                employee = new Employee(); Utils.Helper.SetNullToEmptyString(employee);
                if (HttpContext.Current.Request["IsCreate"] != "true")
                {
                    int id = 0;
                    try
                    {
                        id = Convert.ToInt32(HttpContext.Current.Request["idem"]);
                    }
                    catch { }
                    strUri = Global.ServiceUriDictionary["employeedetail"] + id + Global.ServiceUriDictionary["requestformat"];
                    ///Get Rest///
                    stringReader = base.RestService.GetJson(strUri);
                    employee = JsonConvert.DeserializeObject<Employee>(stringReader.ReadToEnd());
                }

                employee.PostHandler<HISModels.Entities.Employee>();


                strUri = Global.ServiceUriDictionary["employee"] + Global.ServiceUriDictionary["requestformat"];

                if (HttpContext.Current.Request["IsCreate"] == "true")
                {
                    stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(employee));
                }
                else
                {
                    stringReader = base.RestService.PutJson(strUri, JsonConvert.SerializeObject(employee));
                }
                string temp = stringReader.ReadToEnd();


                employee = JsonConvert.DeserializeObject<Employee>(temp);

                if (employee != null)
                {
                    strNotification = Helper.SuccessMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                }
                else
                {
                    strNotification = Helper.ErrorMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                }


                strNotification = "{\"strNotification\": \"" + strNotification + "\"}";
                HttpContext.Current.Response.Write(strNotification);

            }
            catch (Exception ex)
            {
                //strNotification = "{\"strNotification\": \"" + ex.Message + "\"}";
                HttpContext.Current.Response.Write(ex.Message);
            }
            finally
            {

                base.RestService.Dispose();
            }
        }

        [Authorization(RoleAction = "master-items")]

        public void CreateEmployee()
        {
            employee = new Employee();
            Utils.Helper.SetNullToEmptyString(employee);
            try
            {
                Data["Pagetitle"] += " :: Add Employee";
                employee = new HISModels.Entities.Employee() { EmployeeNumber = string.Empty, SuperiorNumber = string.Empty, FirstName = string.Empty, LastName = string.Empty, };
                Data.Add("ddlLocation", DropDownLocation(""));
                Data.Add("ddlDepartment", DropDownDepartment(""));
                Data.Add("ddlGender", Utils.Helper.GetGender("GenderId", "class=required", string.Empty));
                Data.Add("employee", employee);
                Data.Add("IsCreate", "true");
                Data["Notification"] = strNotification;

            }
            catch (Exception ex)
            {
                Data["Notification"] = Helper.ErrorMessage(ex.Message);
            }
            finally
            {
                RenderFile("Master\\employee\\editemployee.html");
                base.RestService.Dispose();
            }
        }

        [Authorization(RoleAction = "master-items")]
        public string DropDownDepartment(string Selected)
        {
            StringReader stringReaderDropDown = null;
            string strResult = string.Empty;
            //string strUri = Data["servicerooturl"] + "sys/roles/?format=json";
            string strUri = Global.ServiceUriDictionary["departementlist"] + Global.ServiceUriDictionary["requestformat"];
            try
            {
                stringReaderDropDown = base.RestService.GetJson(strUri);
                List<Departement> listDep = JsonConvert.DeserializeObject<List<Departement>>(stringReaderDropDown.ReadToEnd());
                List<object[]> activeArr1 = new List<object[]>();

                foreach (Departement item in listDep) activeArr1.Add(new object[] { item.Id, item.NameValue });
                strResult = KeanuMvc.Reference.Html.DropDown("DepartementId", string.Empty, activeArr1, Selected);
                activeArr1.Clear();
                activeArr1 = null;
            }
            catch
            {
            }
            finally
            {
                stringReaderDropDown.Dispose();
            }
            return strResult;
        }
        [Authorization(RoleAction = "master-items")]
        public string DropDownLocation(string Selected)
        {
            StringReader stringReaderDropDown = null;
            string strResult = string.Empty;
            //string strUri = Data["servicerooturl"] + "sys/roles/?format=json";
            string strUri = Global.ServiceUriDictionary["hospital"] + Global.ServiceUriDictionary["requestformat"];
            try
            {
                stringReaderDropDown = base.RestService.GetJson(strUri);
                List<RefHu> listHu = JsonConvert.DeserializeObject<List<RefHu>>(stringReaderDropDown.ReadToEnd());
                List<object[]> activeArr = new List<object[]>();

                foreach (RefHu item in listHu) activeArr.Add(new object[] { item.Id, item.NameValue });
                strResult = KeanuMvc.Reference.Html.DropDown("HospitalUnitId", string.Empty, activeArr, Selected);
                activeArr.Clear();
                activeArr = null;
            }
            catch
            {
            }
            finally
            {
                stringReaderDropDown.Dispose();
            }
            return strResult;
        }


        [Authorization(RoleAction = "master-items")]
        public string DropDownLocation2(string Selected)
        {
            StringReader stringReaderDropDown = null;
            string strResult = string.Empty;
            string Name = string.Empty;
            string strUri = "";
            strUri = Global.ServiceUriDictionary["hospital"] + Global.ServiceUriDictionary["requestformat"];
            try
            {
                stringReaderDropDown = base.RestService.GetJson(strUri);
                List<HISModels.Entities.RefHu> listSp = JsonConvert.DeserializeObject<List<RefHu>>(stringReaderDropDown.ReadToEnd());
                List<object[]> activeArr = new List<object[]>();

                activeArr.Add(new object[] { -1, Name = "- All Location -" });

                foreach (RefHu item in listSp) activeArr.Add(new object[] { item.Id, item.CodeValue + " - " + item.NameValue });

                strResult = KeanuMvc.Reference.Html.DropDown("HospitalUnitId", string.Empty, activeArr, Selected);
                activeArr.Clear();
                activeArr = null;
            }
            catch
            {
            }
            finally
            {
                stringReaderDropDown.Dispose();
            }
            return strResult;
        }

        #endregion

    }

}